(function () {
    class Game {
        constructor (map) {
            this.food = new Food();
            this.snake = new Snake();
            this.map = map
        }

        start () {
            this.food.render(this.map);
            this.food.render(this.map);
            this.food.render(this.map);
            this.snake.render(this.map);
            run(this);
            document.onkeydown = e => {
                switch (e.keyCode) {
                    case 37:
                        this.snake.direction = "left";
                        break;
                    case 38:
                        this.snake.direction = "up";
                        break;
                    case 39:
                        this.snake.direction = "right";
                        break;
                    case 40:
                        this.snake.direction = "down";
                }
            }
        }


    }

    function run (context) {
        var timer = setInterval(function () {
            this.snake.move();
            this.snake.remove();
            this.snake.render(this.map);
            var head = this.snake.body[this.snake.body.length - 1], maxX = this.map.clientWidth / this.snake.width - 1,
            maxY = this.map.clientHeight / this.snake.height - 1,last = this.snake.body[0];
            if (head.x < 0 || head.y <0 || head.x > maxX || head.y > maxY) {
                clearInterval(timer)
                alert("game over")
            }            
            for (var i = 0 ; i < this.food.eles.length ; i++) {
                if (head.x == this.food.eles[i].getAttribute("x") && head.y == this.food.eles[i].getAttribute("y")) {
                    this.food.remove(i);
                    this.food.render(this.map);
                    this.snake.body.unshift({
                        x: last.x,
                        y: last.y,
                        color: last.color
                    });
                }
            }
        }.bind(context),200)
    }
    window.Game = Game;
})()